# Copyright 2012 Google Inc. All Rights Reserved.

"""One-line documentation for gplus-calendar module.

A detailed description of gplus-calendar.
"""

# __author__ = 'motiwala@google.com (Murtaza Motiwala)'

import os
import cgi
import settings
import httplib2
import urllib
import logging

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.template import defaultfilters
from apiclient.discovery import build
from oauth2client.appengine import oauth2decorator_from_clientsecrets
from oauth2client.client import AccessTokenRefreshError
from oauth2client.appengine import OAuth2Decorator
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import OAuth2WebServerFlow
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp import template



CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client.json')

MISSING_CLIENT_SECRETS_MESSAGE = """
<h1>Warning: Please configure OAuth 2.0</h1>
<p>
To make this sample run you will need to populate the client_secrets.json file
found at:
</p>
<p>
<code>%s</code>.
</p>
<p>with information found on the <a
href="https://code.google.com/apis/console">APIs Console</a>.
</p>
""" % CLIENT_SECRETS

class Credentials(db.Model):
  credentials = CredentialsProperty()


decorator = oauth2decorator_from_clientsecrets(
    CLIENT_SECRETS,
    'https://www.googleapis.com/auth/plus.me',
    MISSING_CLIENT_SECRETS_MESSAGE)

http = httplib2.Http(memcache)
httpUnauth = httplib2.Http(memcache)

ul = urllib.urlopen(settings.DISCOVERY_DOCUMENT)
discovery_doc = ul.read()
ul.close()

service = build('plus', 'v1', http=http)

serviceUnauth = build('plus', 'v1', http=http, developerKey=settings.API_KEY)

class MainPage(webapp.RequestHandler):
  
  @decorator.oauth_aware
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'grant.html')
    variables = {
        'url' : decorator.authorize_url(),
        'has_credentials' : decorator.has_credentials()
        }
    self.response.out.write(template.render(path,variables))

class PlayHandler(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if not user:
      self.redirect('/login')

    self.response.out.write("Welcome %s to new reality\n" % (user.user_id()))
    http = decorator.http()
    people = service.people().get(userId='me').execute(http)

    path = os.path.join(os.path.dirname(__file__), 'play.html')

    import pprint
    logging.info(pprint.pformat(people))

    me = service.people().get(userId='me').execute(decorator.http())
    
    activities_doc = service.activities().list(userId=me['id'], collection='public').execute(http)

    activities = []

    if 'items' in activities_doc:
      activities += activities_doc['items']

    top_activity_content = 'No top activity'

    if len(activities) > 0:
      activities_doc = service.activities().get(activityId=activities[0]['id']).execute(http)
      top_activity_content = defaultfilters.striptags(activities_doc['object']['content'])

      self.response.out.write(
          template.render(path, {'me': me, 'activities': activities,
                                 'top_activity_content': top_activity_content}))
    else:
      self.response.out.write(
          template.render(path, {'me': me, 'activities': activities,
                                 'top_activity_content': top_activity_content}))


class LoginPage(webapp.RequestHandler):

  def get(self):
    user = users.get_current_user()
    credentials = StorageByKeyName(Credentials, user.user_id(), 'credentials').get()
    
    if credentials:
      self.response.headers['Content-Type'] = 'text/plain'
      self.response.out.write('Welcome %s to new reality\n' % (user.user_id()))
    else:
      self.redirect(users.create_login_url(self.request.uri))


  def post(self):
    self.redirect('/play')


def main():
  application = webapp.WSGIApplication([('/', MainPage),
                                        ('/play', PlayHandler),
                                        ('/login', LoginPage),
                                        ],
                                       debug=True)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
